package com.magenta.maxoptra.gis.utils;

import com.magenta.maxoptra.gis.commons.Logger;
import com.magenta.maxoptra.gis.GeographicCoordinates;

import java.text.NumberFormat;
import java.util.Locale;

/**
 * Created with IntelliJ IDEA.
 * User: kuznetsovd
 * Date: 05.12.12
 * Time: 13:15
 * To change this template use File | Settings | File Templates.
 */
public abstract class AbstractGisProfiler {
    protected final Logger logger = new Logger(getClass());
    protected final boolean enableProfiling;
    protected long startTime;
    protected long duration;
    protected final String provider;
    protected final String accountGlobalId;
    protected final NumberFormat coordFormat;
    protected final NumberFormat distanceFormat;
    protected String separator = ";";

    public AbstractGisProfiler(String provider, String accountGlobalId,
                               boolean enableProfiling
    ) {
        this.enableProfiling = enableProfiling;
        this.accountGlobalId = (accountGlobalId != null ? accountGlobalId : "UNKNOWN_ACCOUNT");
        this.provider = (provider != null ? provider : "UNKNOWN_PROVIDER");
        this.startTime = enableProfiling ? System.currentTimeMillis() : 0;
        coordFormat = NumberFormat.getInstance(Locale.UK);
        coordFormat.setMaximumFractionDigits(6);

        distanceFormat = NumberFormat.getInstance(Locale.UK);
        distanceFormat.setMaximumFractionDigits(2);
    }

    public void logDuration(String action) {
        if (enableProfiling) {
            long now = System.currentTimeMillis();
            duration = now - startTime;
            logger.info(getInitialInfo() + separator + action + separator+Long.toString(duration)+" ms");
            startTime = now;
        }
    }

    public void logError(String errorMessage) {
        if (enableProfiling) {
            duration = System.currentTimeMillis() - startTime;
            logger.info(getInitialInfo() + separator + errorMessage + separator + Long.toString(duration)+" ms");
        }
    }

    protected String printPoint(GeographicCoordinates c) {
        return "(" + coordFormat.format(c.getLatitude()) + ":" + coordFormat.format(c.getLongitude()) + ")";
    }

    public abstract String getInitialInfo();

    public String getSeparator() {
        return separator;
    }

    public void setSeparator(String separator) {
        this.separator = separator;
    }

    public long getDuration() {
        return duration;
    }

}
